<template>
  <!-- 添加或修改用户配置对话框 -->
  <el-dialog
    :title="title"
    :visible.sync="isOpen"
    append-to-body
    @close="handleClose"
    width="75%"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="auto">
      <el-row>
        <el-col :span="6" class="text-center">
          <ImageUpload v-model="form.avatarUrl" :limit="1"></ImageUpload>
        </el-col>
        <el-col :span="18">
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属部门" prop="deptId">
                <treeselect
                  v-model="form.deptId"
                  :options="deptOptions"
                  placeholder="选择部门"
                  @select="handleDeptSelect"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="岗位" prop="postDict">
                <el-select v-model="form.postDict" placeholder="选择岗位">
                  <el-option v-for="dict in dict.type.biz_civil_servant_post" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="输入姓名"
                  maxlength="10"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="性别" prop="sexDict">
                <el-radio-group v-model="form.sexDict">
                  <el-radio
                    v-for="dict in dict.type.sys_user_sex"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期" prop="birthday">
                <el-date-picker
                  v-model="form.birthday"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择出生日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phone">
                <el-input
                  v-model="form.phone"
                  placeholder="输入手机号码"
                  minlength="11"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类别" prop="personnelTypeDict">
                <el-select
                  v-model="form.personnelTypeDict"
                  placeholder="选择类别"
                >
                  <el-option
                    v-for="dict in dict.type.biz_personnel_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="12">
              <el-form-item label="身份证号" prop="identityCard">
                <el-input v-model="form.identityCard" placeholder="输入身份证号" minlength="18" maxlength="18"  />
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="政治面貌" prop="politicalLandscapeDict">
                <el-select
                  v-model="form.politicalLandscapeDict"
                  placeholder="选择政治面貌"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type
                      .biz_civil_servant_political_landscape"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编制性质" prop="workNatureDict">
                <el-select
                  v-model="form.workNatureDict"
                  placeholder="选择编制性质"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.biz_civil_servant_work_nature"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="职务" prop="positionDict">
                <el-select
                  v-model="form.positionDict"
                  placeholder="选择职务"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.biz_civil_servant_position"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="特殊情况" prop="remarks">
                <el-input
                  v-model="form.remarks"
                  placeholder="特殊情况"
                  maxlength="10"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否纳入绩效管理" prop="assessmentMark">
                <el-radio-group v-model="form.assessmentMark">
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <div class="title">
              <div><i class="el-icon-document"></i> 干部履历</div>
              <el-button
                type="primary"
                plain
                size="mini"
                @click="handlePersonalCareersAdd"
                icon="el-icon-plus"
              >
                新增</el-button
              >
            </div>
            <el-table border style="width: 100%" :data="personalCareersTable">
              <el-table-column label="序号" type="index" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="date" label="日期" align="center">
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.date"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                    :clearable="false"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column prop="type" label="变动" align="center">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.type"
                    placeholder="选择类型"
                    clearable
                  >
                    <el-option
                      v-for="dict in dict.type.biz_personal_career_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="content" label="内容" align="center">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.content"
                    type="textarea"
                    placeholder="输入内容及方式"
                    :rows="1"
                    :autosize="{ minRows: 1, maxRows: 5 }"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="remarks" label="备注" align="center">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.remarks"
                    type="textarea"
                    placeholder="输入内容及方式"
                    :rows="1"
                    :autosize="{ minRows: 1, maxRows: 5 }"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="操作"
                align="center"
                width="140"
                fixed="right"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="mini"
                    @click="handlePersonalCareersUpdate(scope.row)"
                  >
                    修改</el-button
                  >
                  <el-button
                    type="text"
                    class="color-danger"
                    size="mini"
                    @click="handlePersonalCareersDelete(scope.row)"
                  >
                    删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>
    <PersonalCareersAdd
      :visible.sync="personalCareersAddVisible"
      :params="{ id: form.id }"
      @success="getCareersList"
    ></PersonalCareersAdd>
  </el-dialog>
</template>

<script>
import { detail, add, update } from "@/api/organization/civil-servant";
import { deptTreeSelectV2 as deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ImageUpload from "@/components/ImageUpload";
import PersonalCareersAdd from "./PersonalCareersAdd.vue";
import {
  list as careersList,
  update as careersUpdate,
  remove as careersRemove,
} from "@/api/organization/civil-servant/careers.js";
export default {
  name: "civil-servant-edit",
  dicts: [
    "biz_personnel_type",
    "sys_user_sex",
    "biz_civil_servant_post",
    "biz_civil_servant_special_situation",
    "biz_civil_servant_position",
    "biz_civil_servant_rank",
    "biz_civil_servant_political_landscape",
    "biz_civil_servant_work_nature",
    "biz_personal_career_type",
  ],
  components: { Treeselect, ImageUpload, PersonalCareersAdd },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    params: {
      type: Object,
      default: () => {},
    },
    operation: {
      type: String,
      default: "add",
    },
  },
  data() {
    return {
      personalCareersAddVisible: false,
      personalCareersItem: {
        date: "",
        type: "",
        content: "",
        remarks: "",
      },
      personalCareersTable: [],
      disabled: true, // 是否不可编辑
      form: {
        id: "",
        avatarUrl: "",
        deptId: undefined,
        deptName: undefined,
        name: undefined,
        identityCard: undefined,
        avatarUrl: undefined,
        phone: undefined,
        sexDict: undefined,
        birthday: undefined,
        assessmentMark: undefined,
        personnelTypeDict: undefined,
        postDict: undefined,
        positionDict: undefined,
        rankDict: undefined,
        specialSituationDict: undefined,
        orderNum: undefined,
        remarks: undefined,
        politicalLandscapeDict: undefined,
        workNatureDict: undefined,
      },
      title: "用户操作",
      isOpen: false,
      // 部门树选项
      deptOptions: undefined,
      // 表单校验
      rules: {
        deptId: [{ required: true, message: "部门不能为空", trigger: "blur" }],
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          {
            pattern: /^[\u4e00-\u9fa5]+$/,
            message: "只能输入中文字符",
            trigger: "change",
          },
        ],
        identityCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          { validator: this.checkIdentityCard, trigger: "blur" },
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式错误",
            trigger: "blur",
          },
        ],
        // sexDict: [{ required: true, message: '性别不能为空', trigger: 'change' }],
        // birthday: [{ required: true, message: '出生日期不能为空', trigger: 'change' }],
        assessmentMark: [
          {
            required: true,
            message: "是否纳入绩效管理不能为空",
            trigger: "change",
          },
        ],
        personnelTypeDict: [
          { required: true, message: "人员类别不能为空", trigger: "change" },
        ],
        workNatureDict: [
          { required: true, message: "编制性质不能为空", trigger: "change" },
        ],
        politicalLandscapeDict: [
          { required: true, message: "政治面貌不能为空", trigger: "change" },
        ],
        // positionDict: [{ required: true, message: '职务不能为空', trigger: 'change' }],
        // rankDict: [{ required: true, message: '职级不能为空', trigger: 'change' }]
      },
    };
  },
  watch: {
    visible: {
      handler(val) {
        this.isOpen = val;
        if (val) {
          this.getDeptTree();
          if (this.operation === "update") {
            this.title = `[ ${this.params.name} ]信息更新`;
            this.getDetail();
          } else if (this.operation === "add") {
            this.title = "新增用户信息";
          }
        }
      },
    },
  },
  methods: {
    getCareersList() {
      careersList({ civilServantId: this.form.id }).then((res) => {
        this.personalCareersTable = res.rows;
      });
    },
    handlePersonalCareersAdd() {
      this.personalCareersAddVisible = true;
    },
    handlePersonalCareersUpdate(val) {
      let { id, civilServantId, date, type, content, remarks } = val;
      careersUpdate({ id, civilServantId, date, type, content, remarks }).then(
        (res) => {
          this.$modal.msgSuccess("已修改");
        }
      );
    },
    handlePersonalCareersDelete(val) {
      let removeContent = `您正在删除【${val.date}】记录数据`;
      this.$confirm(
        `${removeContent}，数据删除后将无法找回，请确认删除`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          beforeClose: (action, instance, done) => {
            if (action === "confirm") {
              const loading = this.$loading({
                target: ".el-message-box",
                lock: true,
                text: "正在删除...",
                spinner: "el-icon-loading",
                background: "rgba(255,255,255,0.6)",
              });
              careersRemove({ id: val.id })
                .then((res) => {
                  this.getCareersList();
                  this.$modal.msgSuccess("已删除");
                  done();
                })
                .catch(() => {
                  loading.close();
                  done();
                });
            } else {
              done();
            }
          },
        }
      );
    },
    // 身份证号校验
    checkIdentityCard(rule, value, callback) {
      const regExp =
        /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;
      if (regExp.test(value)) {
        this.form.birthday = [
          value.substr(6, 4),
          value.substr(10, 2),
          value.substr(12, 2),
        ].join("-");
        this.form.sexDict = String(value.substr(14, 1) % 2);
        callback();
      } else {
        callback(new Error("身份证号格式错误"));
      }
    },
    handleDeptSelect(raw) {
      let { deptName, deptId } = raw;
      this.form.deptId = deptId;
      this.form.deptName = deptName;
    },
    getDetail() {
      detail({ id: this.params.id }).then((res) => {
        let { data } = res;
        ({ ...this.form } = data);
        this.getCareersList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.operation === "update") {
            update(this.form).then((res) => {
              this.$modal.msgSuccess("已更新");
              this.$emit("success");
            });
          } else {
            add(this.form).then((res) => {
              this.$modal.msgSuccess("已新增");
              this.handleClose();
              this.$emit("success");
            });
          }
        }
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 关闭弹框
    handleClose() {
      this.reset();
      this.$emit("update:visible", false);
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        name: undefined,
        password: undefined,
        phone: undefined,
        email: undefined,
        sex: undefined,
        personnelTypeDict: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
  },
};
</script>

<style scoped>
::v-deep .el-date-editor {
  width: auto !important;
}
.el-upload__tip {
  text-align: left;
}
.title {
  font-size: 18px;
  font-weight: bold;
  padding: 20px 0;
  color: #409eff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
